﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Reflection;
using System.Text;
using System.Collections;
using System.Diagnostics;
using System.Web.Hosting;
using System.IO;


namespace HQWeb.View
{
    public partial class ViewList : BasePage
    {
        private DataTable data;
        private static bool bindFalg;   //是否选择订单后直接绑定数据
        private static string all_ProjectID;
        private static Dictionary<string, string> ProjectID_No;
        protected void Page_Load(object sender, EventArgs e)
        {
            VerdictIsLogin();
            // EditProject = "";
            if (!IsPostBack)
            {
                if (Session["USER_ID"] == null)
                {
                    new Exception("请重新登入");
                }
                BindDropList();
                BindStyle();
                hidOrderID.Value = "";
                ProjectID_No = new Dictionary<string, string>();
                all_ProjectID = "";
                bindFalg = false;
                txtTotal.Attributes["ReadOnly"] = "true";
            }
        }

        #region 页面处理

        //填充风格
        private void BindStyle()
        {
            StringBuilder strHtml = new StringBuilder();

            BLL.SysManage.T_PUB_DICTIONARY bll = new BLL.SysManage.T_PUB_DICTIONARY();
            List<Model.SysManage.T_PUB_DICTIONARY> il = bll.GetListArray(" FLAG = 1 and PARENT_ID = 5 order by ORDER_ID");
            strHtml.Append("  <table width=\"90%\" border='0px'>");
            int count = il.Count();
            int tempValue;
            for (int j = 0; j <= (count - 1) / 5; j++)
            {
                int i = 0;
                strHtml.Append(" <tr>");
                for (; i < 5 && 5 * j + i < count; i++)
                {
                    tempValue = 5 * j + i;
                    string strName = il.ElementAt(tempValue).NAME;
                    string strId = il.ElementAt(tempValue).ID.ToString();
                    //int temp = 5 * j + i;
                    strHtml.Append("<td align=\"left\" style=\"width:20%\">");
                    strHtml.Append(" <input type=\"checkbox\" name='checkBoxName' style\" id=\"" + strId + "\" value=\"" + strId + "\"/>");
                    strHtml.Append(strName);
                    strHtml.Append("</td>");
                }
                if ((5 - i) > 0)
                {
                    int sy = 5 - i;
                    strHtml.Append("<td colspan=" + sy + ">");
                    strHtml.Append("</td>");
                }
            }
            strHtml.Append(" </table>");
            controls.InnerHtml = strHtml.ToString();
        }

        //绑定下拉列表框 
        private void BindDropList()
        {
            BLL.SysManage.T_PUB_DICTIONARY dictBll = new BLL.SysManage.T_PUB_DICTIONARY();
            List<Model.SysManage.T_PUB_DICTIONARY> modelList = dictBll.GetListArray("  FLAG = 1 and parent_id in ( '2','19','142','6')");
            orderType.DataSource = modelList.Where(p => p.PARENT_ID == 2);
            orderType.DataTextField = "name";
            orderType.DataValueField = "ID";
            orderType.DataBind();

            dropFrom.DataSource = modelList.Where(p => p.PARENT_ID == 19);
            dropFrom.DataTextField = "name";
            dropFrom.DataValueField = "ID";
            dropFrom.DataBind();

            MemorialType.DataSource = modelList.Where(p => p.PARENT_ID == 142);
            MemorialType.DataTextField = "name";
            MemorialType.DataValueField = "ID";
            MemorialType.DataBind();
            MemorialType.Items.Insert(0, new ListItem("--请选择--", ""));

            dropPrice.DataSource = modelList.Where(p => p.PARENT_ID == 6);
            dropPrice.DataTextField = "name";
            dropPrice.DataValueField = "ID";
            dropPrice.DataBind();
            dropPrice.Items.Insert(0, new ListItem("--请选择--", ""));
        }


        //编辑时页面填充
        private void FillPage(string strOrderID)
        {
            BLL.Order.T_PUB_ORDER orderBll = new BLL.Order.T_PUB_ORDER();
            Model.Order.T_PUB_ORDER orderModel = orderBll.GetModelByID(strOrderID);
            if (orderModel != null)
            {
                string strType = orderModel.Type.ToString();
                if (orderType.Items.FindByValue(strType) != null)
                {
                    orderType.SelectedValue = strType;
                }
                if (orderModel.OrderDate != null)
                {
                    d12.Value = Convert.ToDateTime(orderModel.OrderDate).ToShortDateString();
                }
                string strMemorialType = orderModel.MemorialType.ToString();
                if (MemorialType.Items.FindByValue(strMemorialType) != null)
                {
                    MemorialType.SelectedValue = strMemorialType;
                }
                if (orderModel.MemorialDay != null)
                {
                    MemorialDate.Value = Convert.ToDateTime(orderModel.MemorialDay).ToString("yyyy-MM-dd");
                }
                string strPrice = orderModel.WeedPrice.ToString();
                if (dropPrice.Items.FindByValue(strPrice) != null)
                {
                    dropPrice.SelectedValue = strPrice;
                }
                string strDateOther = orderModel.DateOther;
                dropDate.SelectedValue = strDateOther;
                txtOther.Text = orderModel.Other;
                hidStytle.Value = orderModel.STYLE_IDS;
                if (Request.Cookies["shopcar"] != null)
                {
                    Request.Cookies.Remove("shopcar ");
                }
                else
                {

                }
                bindFalg = true;
                string strCooiesValue = SetCookies(orderModel.ORDER_ID);
                HttpCookie acookie = new HttpCookie("shopcar");
                acookie.Value = strCooiesValue;
                acookie.Expires = DateTime.MaxValue;

                Response.Cookies.Add(acookie);
                hidOldProjectID.Value = orderModel.PROJECT_IDS;    //保存旧的项目
                hidOldDinJin.Value = orderModel.DingJin.ToString(); //保存旧的定金
                txtDinJin.Text = orderModel.DingJin.ToString();
                textRealTotal.Text = orderModel.RealToal.ToString();
                if (orderModel.Total != null)
                {
                    txtUnpaid.Text = (orderModel.RealToal - orderModel.Total).ToString();
                }
                else
                {
                    txtUnpaid.Text = orderModel.RealToal.ToString();
                }

                BLL.View.T_PUB_CUSTOMERINFO coustomerBll = new BLL.View.T_PUB_CUSTOMERINFO();
                Model.View.T_PUB_CUSTOMERINFO coustomModel = coustomerBll.GetModel(orderModel.CUSTOMER_ID);
                //  EditProject = orderModel.PROJECT_IDS;
                if (coustomModel != null)
                {
                    txtBRIDE_NAME.Text = coustomModel.BRIDE_NAME;
                    txtBRIDEADDRESS.Text = coustomModel.BRIDEADDRESS;
                    txtBRIDEAGE.Text = coustomModel.BRIDEAGE.ToString();
                    txtBRIDEPHONE.Text = coustomModel.BRIDEPHONE;
                    txtBRIDEPOST.Text = coustomModel.BRIDEPOST;
                    txtBRIDEQQ.Text = coustomModel.BRIDEQQ;
                    txtGROOM_NAME.Text = coustomModel.GROOM_NAME;
                    txtGROOMAGE.Text = coustomModel.GROOMAGE.ToString();
                    txtGROOMPHONE.Text = coustomModel.GROOMPHONE;
                    txtGROOMPOST.Text = coustomModel.GROOMPOST;
                    txtGROOMQQ.Text = coustomModel.GROOMQQ;
                    txtHOUSEADDRESS.Text = coustomModel.HOUSEADDRESS;
                    //以下信息可以通过tbody控制
                    txtMARRIAGECAR.Text = coustomModel.MARRIAGECAR;
                    txtHotelManage.Text = orderModel.HotelManage;
                    txtRANK.Text = coustomModel.RANK.ToString();
                    txtTABLENUM.Text = coustomModel.TABLENUM.ToString();
                    d12.Value = Convert.ToDateTime(coustomModel.TIME).ToShortDateString().Replace('/', '-');
                    txtWEDDING.Text = coustomModel.WEDDING;
                    txtYOUNGER.Text = coustomModel.YOUNGER.ToString();
                    txtELDER.Text = coustomModel.ELDER.ToString();
                    Text1.Value = coustomModel.HOTEL;
                }
                GetData();
                BianGV1();
                ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "clear", " <script type=\"text/javascript\" language=\"javascript\"> RefreshShopCar();</script>", false);
                ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "UpdatePanel1", "<script type=\"text/javascript\" language=\"javascript\">EditFillStyle('"+orderModel.STYLE_IDS+"');</script>", false);

            }
        }
        //编辑时
        private string SetCookies(string strOrderID)
        {
            string strResout = "";
            BLL.Order.T_PUB_Order_Project bll = new BLL.Order.T_PUB_Order_Project();
            List<Model.Order.T_PUB_Order_Projectcs> list = bll.GetOrderProject(strOrderID);
            all_ProjectID = "";
            ProjectID_No.Clear();
            foreach (Model.Order.T_PUB_Order_Projectcs item in list)
            {
                all_ProjectID = all_ProjectID + item.ProjectID + ",";
                ProjectID_No.Add(item.ProjectID, item.Number.ToString());
                strResout = strResout + item.ProjectID + "|" + item.Number.ToString() + ",";
            }
            return strResout;
        }

        //选择订单后填充页面
        protected void GetOrder_Click(object sender, EventArgs e)
        {
            string strOrderID = hidOrderID.Value;
            Session["OrderID"] = strOrderID;
            FillPage(strOrderID);
            btn_Submit.Visible = false;
            Button1.Visible = true;
            hidRunState.Value = "0";
        }

        //弹出订单时绑定项目数据
        protected void GetProject_Click(object sender, EventArgs e)
        {
            bindFalg = false;
            GetData();
            BianGV1();
            hidRunState.Value = "0";
        }

        #endregion

        #region 数据绑定

        /// <summary>
        /// 得到所有数据源
        /// </summary>
        private void GetData()
        {
            if (true)
            {

            }
            if (!bindFalg)
            {
                if (Request.Cookies["shopcar"] != null)
                {
                    getCooikesValue(Request.Cookies["shopcar"].Value);
                }

            }

            string strBranchID = Session["BRANCH_ID"].ToString();
            BLL.Progect.T_PUB_PROJECT bll = new BLL.Progect.T_PUB_PROJECT();
            data = bll.GetOrderProject(strBranchID, all_ProjectID);
        }

        //主表数据绑定
        private void BianGV1()
        {
            //  string strName = txtName.Text.Trim();
            DataTable datable = new DataTable();

            var dataSource = (from v in data.AsEnumerable() select new { a = v.Field<string>("PROJECT_ID"), b = v.Field<string>("PROJECT_NAME"), c = v.Field<int?>("PRICE"), d = v.Field<string>("PROJECTTYPE_NAME") }).Distinct();
            // txtTotal.Text = dataSource.Sum(p => p.c).ToString();
            datable = ConvertToTable(dataSource);
            if (datable.Rows.Count > 0)
            {
                BLL.Progect.T_PUB_PROJECTFILE projectBll = new BLL.Progect.T_PUB_PROJECTFILE();
                DataTable ImageTable = projectBll.GetProjectImageUrl(all_ProjectID);
                AddUrl(datable, ImageTable);
                GridView1.DataSource = datable;
                GridView1.DataBind();
            }
            else
            {
                GridView1.DataSource = null;
                GridView1.DataBind();
            }
        }

        //添加项目图片路径和数量    
        private void AddUrl(DataTable dt, DataTable urldt)
        {
            dt.Columns.Add("URLThumbnail", typeof(string));
            dt.Columns.Add("URLOriginal", typeof(string));
            dt.Columns.Add("TYPE", typeof(string));
            dt.Columns.Add("Number", typeof(string));
            int dtCount = dt.Rows.Count;
            DataRow[] dataRows;
            DataRow rowTemp;
            decimal totalMoney = 0;
            string strType = "";
            string strUrl = "";
            for (int i = 0; i < dtCount; i++)
            {
                rowTemp = dt.Rows[i];
                string strRowID = rowTemp["a"].ToString();
                dataRows = urldt.Select(string.Format(" PROJECT_ID='{0}'", rowTemp["a"]));
                if (dataRows.Length > 0)
                {
                    strType = dataRows[0]["TYPE"].ToString();
                    if (strType == "1")
                    {
                        strUrl = dataRows[0]["URLThumbnail"].ToString();
                    }
                    else
                    {
                        strUrl = dataRows[0]["URLThumbnail"].ToString();
                    }
                    rowTemp["URLThumbnail"] = "../../" + strUrl.Replace("//", "/");
                    rowTemp["URLOriginal"] = dataRows[0]["URLOriginal"];
                    rowTemp["TYPE"] = strType;
                }
                else
                {
                    rowTemp["URLThumbnail"] = "";
                    rowTemp["URLOriginal"] = "";
                    rowTemp["TYPE"] = "";
                }

                if (ProjectID_No.ContainsKey(strRowID))
                {
                    string strPrice = rowTemp["c"].ToString();
                    string strNumber = ProjectID_No[strRowID];
                    rowTemp["Number"] = strNumber;
                    decimal decPrice;
                    decimal decNumber;
                    decimal.TryParse(strPrice, out decPrice);
                    decimal.TryParse(strNumber, out decNumber);
                    totalMoney = totalMoney + decPrice * decNumber;

                }
                // rowTemp["PRICE"]
            }
            txtTotal.Text = totalMoney.ToString();
        }

        /// <summary>
        /// 转化为datatable
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>

        private DataTable ConvertToTable(IEnumerable<object> query)
        {
            DataTable dtList = new DataTable();
            bool isAdd = false;
            PropertyInfo[] objProterties = null;
            foreach (var item in query)
            {
                if (!isAdd)
                {
                    objProterties = item.GetType().GetProperties();
                    foreach (var itemProterty in objProterties)
                    {
                        Type type = null;
                        if (itemProterty.PropertyType != typeof(string) && itemProterty.PropertyType != typeof(int) && itemProterty.PropertyType != typeof(DateTime))
                        {
                            type = typeof(string);
                        }
                        else
                        {
                            type = itemProterty.PropertyType;
                        }
                        dtList.Columns.Add(itemProterty.Name, type);
                    }
                    isAdd = true;
                }
                var row = dtList.NewRow();
                foreach (var pi in objProterties)
                {
                    row[pi.Name] = pi.GetValue(item, null);
                }
                dtList.Rows.Add(row);
            }

            return dtList;
        }

        //cooikes值处理
        private void getCooikesValue(string strValue)
        {
            all_ProjectID = "";

            ProjectID_No.Clear();
            if (strValue != "")
            {
                strValue = strValue.Replace("%2C", ",");
                strValue = strValue.Replace("%7C", "|");
                string[] strID_NOArry;
                string[] strProjectArry = strValue.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string item in strProjectArry)
                {
                    strID_NOArry = item.Split('|');
                    all_ProjectID = all_ProjectID + strID_NOArry[0] + ",";
                    ProjectID_No.Add(strID_NOArry[0], strID_NOArry[1]);
                }
            }
        }

        /// <summary>
        /// 显示子表数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {

            GridViewRow row = e.Row;
            if (row.DataItem == null)
            {
                return;
            }
            GridView gv = new GridView();
            gv = (GridView)row.FindControl("GridView2");
            if (string.IsNullOrEmpty(gv.UniqueID))
            {
                gv.PageIndex = 0;
                gv.EditIndex = -1;
                ClientScript.RegisterStartupScript(GetType(), "Expand", "<SCRIPT LANGUAGE='javascript'>expandcollapse('div" + ((DataRowView)e.Row.DataItem)["a"].ToString() + "','one');</script>");
            }
            try
            {
                string strPid = Convert.ToString(((DataRowView)e.Row.DataItem)["a"]);
                DataTable ds = new DataTable();
                var dataSource = (from v in data.AsEnumerable() where v.Field<string>("PROJECT_ID") == strPid select new { a = v.Field<int?>("ID"), b = v.Field<int?>("NUM"), c = v.Field<string>("MATERIAL_NAME") }).Distinct();
                if (dataSource.All(p => p.a != null))
                {
                    ds = ConvertToTable(dataSource);
                    if (ds.Rows.Count > 0)
                    {
                        gv.DataSource = ds.DefaultView;
                        gv.DataBind();
                    }
                }
            }
            catch (Exception ex)
            {
                Universal.JS.Alert(ex.Message);
                return;
            }


        }

        #endregion

        #region 翻页事件
        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                //strWhere = strWhere.Replace("order by operatetime DESC", "");
                int newPageIndex = 0;

                if (-2 == e.NewPageIndex)
                { // when click the "GO" Button
                    TextBox txtNewPageIndex = null;
                    GridViewRow pagerRow = GridView1.Controls[0].Controls[GridView1.Controls[0].Controls.Count - 1] as GridViewRow; // refer to PagerTemplate
                    //GridViewRow pagerRow = GridView1.BottomPagerRow; //GridView较DataGrid提供了更多的API，获取分页块可以使用BottomPagerRow 或者TopPagerRow，当然还增加了HeaderRow和FooterRow
                    if (null != pagerRow)
                    {
                        txtNewPageIndex = pagerRow.FindControl("txtNewPageIndex") as TextBox;   // refer to the TextBox with the NewPageIndex value
                    }

                    if (null != txtNewPageIndex)
                    {
                        newPageIndex = int.Parse(txtNewPageIndex.Text) - 1; // get the NewPageIndex
                    }

                    newPageIndex = newPageIndex < 0 ? 0 : newPageIndex;
                    newPageIndex = newPageIndex >= GridView1.PageCount ? GridView1.PageCount - 1 : newPageIndex;
                    GridView1.PageIndex = newPageIndex;
                }
                else if (e.NewPageIndex == -1)
                {
                    newPageIndex = 0;
                    GridView1.PageIndex = 0;
                }
                else
                {  // when click the first, last, previous and next Button
                    newPageIndex = e.NewPageIndex;
                    GridView1.PageIndex = e.NewPageIndex;
                }

                // check to prevent form the NewPageIndex out of the range


                BianGV1();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        #endregion

        #region 按钮事件

        //添加提交
        protected void btn_Submit_Click(object sender, EventArgs e)
        {
            try
            {

                Model.View.T_PUB_CUSTOMERINFO model = new Model.View.T_PUB_CUSTOMERINFO();
                model.BRIDE_NAME = txtBRIDE_NAME.Text.Trim();
                model.BRIDEADDRESS = txtBRIDEADDRESS.Text.Trim();
                if (txtBRIDEAGE.Text.Trim() != "")
                {
                    model.BRIDEAGE = int.Parse(txtBRIDEAGE.Text.Trim());
                }
                model.BRIDEPHONE = txtBRIDEPHONE.Text.Trim();
                model.BRIDEPOST = txtBRIDEPOST.Text.Trim();
                model.BRIDEQQ = txtBRIDEQQ.Text.Trim();
                model.GROOM_NAME = txtGROOM_NAME.Text.Trim();
                if (txtGROOMAGE.Text.Trim() != "")
                {
                    model.GROOMAGE = int.Parse(txtGROOMAGE.Text.Trim());
                }
                model.GROOMPHONE = txtGROOMPHONE.Text.Trim();
                model.GROOMPOST = txtGROOMPOST.Text.Trim();
                model.GROOMQQ = txtGROOMQQ.Text.Trim();
                model.HOUSEADDRESS = txtHOUSEADDRESS.Text.Trim();
                //以下信息可以通过tbody来控制是否显示
                model.MARRIAGECAR = txtMARRIAGECAR.Text.Trim();
                if (txtRANK.Text.Trim() != "")
                {
                    model.RANK = Convert.ToInt32(txtRANK.Text.Trim());
                }
                if (txtTABLENUM.Text.Trim() != "")
                {
                    model.TABLENUM = Convert.ToInt32(txtTABLENUM.Text.Trim());
                }
                if (d12.Value != "")
                {
                    model.TIME = Convert.ToDateTime(d12.Value);
                }
                model.WEDDING = txtWEDDING.Text.Trim();
                if (txtYOUNGER.Text.Trim() != "")
                {
                    model.YOUNGER = Convert.ToInt32(txtYOUNGER.Text.Trim());
                }
                if (txtELDER.Text.Trim() != "")
                {
                    model.ELDER = Convert.ToInt32(txtELDER.Text.Trim());
                }

                model.HOTEL = Text1.Value.Trim();

                Model.Order.T_PUB_ORDER orderModel = new Model.Order.T_PUB_ORDER();
                orderModel.OrderDate = model.TIME;
                orderModel.DateOther = dropDate.SelectedValue;
                string strPric = dropPrice.SelectedValue;
                if (strPric != null)
                {
                    orderModel.WeedPrice = strPric;
                }
                string strDinJin = txtDinJin.Text.Trim();
                if (strDinJin != "")
                {
                    orderModel.DingJin = Convert.ToDecimal(strDinJin);
                    orderModel.Total = orderModel.DingJin;
                }
                string strRealTotal = textRealTotal.Text.Trim();
                if (strRealTotal != "")
                {
                    orderModel.RealToal = Convert.ToDecimal(strRealTotal);

                }
                orderModel.Reception = Convert.ToInt32(Session["USER_ID"].ToString());
                orderModel.BranchID = Convert.ToInt32(Session["BRANCH_ID"]);
                orderModel.Source = dropFrom.SelectedValue;
                orderModel.STYLE_IDS = hidStytle.Value;
                orderModel.Type = Convert.ToInt32(orderType.SelectedValue);
                orderModel.Other = txtOther.Text.Trim();
                orderModel.IsDelete = "0";
                orderModel.HotelManage = txtHotelManage.Text.Trim();
                string strMemorialType = MemorialType.SelectedValue;
                if (strMemorialType != "")
                {
                    orderModel.MemorialType = Convert.ToInt32(strMemorialType);
                }
                string strMemorialDate = MemorialDate.Value.Trim();
                if (strMemorialDate != "")
                {
                    orderModel.MemorialDay = Convert.ToDateTime(strMemorialDate);
                }
                BLL.Order.T_PUB_ORDER orderBll = new BLL.Order.T_PUB_ORDER();
                if (Request.Cookies["shopcar"] != null)
                {
                    getCooikesValue(Request.Cookies["shopcar"].Value);
                }
                orderModel.PROJECT_IDS = all_ProjectID;
                string strOrderID = System.Guid.NewGuid().ToString();
                orderModel.ORDER_ID = strOrderID;
                hidOrderID.Value = strOrderID;
             
                orderBll.AddOrder(orderModel, model, ProjectID_No);

            }
            catch (Exception ex)
            {

                ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "clear", " <script type=\"text/javascript\" language=\"javascript\"> alert('保存出现异常')</script>", false);
                throw new Exception(ex.Message);
            }
            ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "clear", " <script type=\"text/javascript\" language=\"javascript\"> alert('添加成功')</script>", false);
            ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "UpdatePanel1", "<script type=\"text/javascript\" language=\"javascript\">EditFillStyle('" + hidStytle.Value + "');</script>", false);
            btn_Submit.Visible = false;
            Button1.Visible = true;
            hidRunState.Value = "0";
        }

        //修改
        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {

                BLL.Order.T_PUB_ORDER orderBll = new BLL.Order.T_PUB_ORDER();
                Model.Order.T_PUB_ORDER orderModel = orderBll.GetModelByID(hidOrderID.Value);
                BLL.View.T_PUB_CUSTOMERINFO coustromBll = new BLL.View.T_PUB_CUSTOMERINFO();
                Model.View.T_PUB_CUSTOMERINFO model = coustromBll.GetModel(orderModel.CUSTOMER_ID);
                model.BRIDE_NAME = txtBRIDE_NAME.Text.Trim();
                model.BRIDEADDRESS = txtBRIDEADDRESS.Text.Trim();
                if (txtBRIDEAGE.Text.Trim() != "")
                {
                    model.BRIDEAGE = int.Parse(txtBRIDEAGE.Text.Trim());
                }
                model.BRIDEPHONE = txtBRIDEPHONE.Text.Trim();
                model.BRIDEPOST = txtBRIDEPOST.Text.Trim();
                model.BRIDEQQ = txtBRIDEQQ.Text.Trim();
                model.GROOM_NAME = txtGROOM_NAME.Text.Trim();
                if (txtGROOMAGE.Text.Trim() != "")
                {
                    model.GROOMAGE = int.Parse(txtGROOMAGE.Text.Trim());
                }
                model.GROOMPHONE = txtGROOMPHONE.Text.Trim();
                model.GROOMPOST = txtGROOMPOST.Text.Trim();
                model.GROOMQQ = txtGROOMQQ.Text.Trim();
                model.HOUSEADDRESS = txtHOUSEADDRESS.Text.Trim();
                //以下信息可以通过tbody来控制是否显示
                model.MARRIAGECAR = txtMARRIAGECAR.Text.Trim();
                if (txtRANK.Text.Trim() != "")
                {
                    model.RANK = Convert.ToInt32(txtRANK.Text.Trim());
                }
                if (txtTABLENUM.Text.Trim() != "")
                {
                    model.TABLENUM = Convert.ToInt32(txtTABLENUM.Text.Trim());
                }
                if (d12.Value != "")
                {
                    model.TIME = Convert.ToDateTime(d12.Value);
                }
                model.WEDDING = txtWEDDING.Text.Trim();
                if (txtYOUNGER.Text.Trim() != "")
                {
                    model.YOUNGER = Convert.ToInt32(txtYOUNGER.Text.Trim());
                }
                if (txtELDER.Text.Trim() != "")
                {
                    model.ELDER = Convert.ToInt32(txtELDER.Text.Trim());
                }
                model.HOTEL = Text1.Value.Trim();

                orderModel.OrderDate = model.TIME;
                orderModel.DateOther = dropDate.SelectedValue;
                string strPric = dropPrice.SelectedValue;
                if (strPric != null)
                {
                    orderModel.WeedPrice = strPric;
                }
                string strDinJin = txtDinJin.Text.Trim();
                if (strDinJin != "")
                {
                    orderModel.DingJin = Convert.ToDecimal(strDinJin);
                    orderModel.Total = orderModel.DingJin;
                }
                string strRealTotal = textRealTotal.Text.Trim();
                if (strRealTotal != "")
                {
                    orderModel.RealToal = Convert.ToDecimal(strRealTotal);

                }

                orderModel.Source = dropFrom.SelectedValue;
                orderModel.STYLE_IDS = hidStytle.Value;
                orderModel.Type = Convert.ToInt32(orderType.SelectedValue);
                orderModel.Other = txtOther.Text.Trim();
                orderModel.HotelManage = txtHotelManage.Text.Trim();
                string strMemorialType = MemorialType.SelectedValue;
                if (strMemorialType != "")
                {
                    orderModel.MemorialType = Convert.ToInt32(strMemorialType);
                }
                string strMemorialDate = MemorialDate.Value.Trim();
                if (strMemorialDate != "")
                {
                    orderModel.MemorialDay = Convert.ToDateTime(strMemorialDate);
                }
                if (Request.Cookies["shopcar"] != null)
                {
                    getCooikesValue(Request.Cookies["shopcar"].Value);
                }
                orderModel.PROJECT_IDS = all_ProjectID;
                decimal oldMoney = 0;
                if (hidOldDinJin.Value != "")
                {
                    oldMoney = Convert.ToDecimal(hidOldDinJin.Value);
                }
               
                orderBll.EditOrder(orderModel, model, ProjectID_No, oldMoney, Session["USER_ID"].ToString());
                hidRunState.Value = "0";

            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "clear", " <script type=\"text/javascript\" language=\"javascript\"> alert('保存出现异常')</script>", false);
                throw new Exception(ex.Message);
            }
            ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "clear", " <script type=\"text/javascript\" language=\"javascript\"> alert('修改成功')</script>", false);
            ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "UpdatePanel1", "<script type=\"text/javascript\" language=\"javascript\">EditFillStyle('" + hidStytle.Value + "');</script>", false);
           
        }

        //清除
        protected void btnClanle_Click(object sender, EventArgs e)
        {

            orderType.SelectedIndex = 0;

            d12.Value = "";

            dropDate.SelectedIndex = 0;
            txtOther.Text = "";
            hidStytle.Value = "";

            hidOldProjectID.Value = "";
            hidOldDinJin.Value = "";
            txtDinJin.Text = "";
            textRealTotal.Text = "";

            txtUnpaid.Text = "";
            txtBRIDE_NAME.Text = "";
            txtBRIDEADDRESS.Text = "";
            txtBRIDEAGE.Text = "";
            txtBRIDEPHONE.Text = "";
            txtBRIDEPOST.Text = "";
            txtBRIDEQQ.Text = "";
            txtGROOM_NAME.Text = "";
            txtGROOMAGE.Text = "";
            txtGROOMPHONE.Text = "";
            txtGROOMPOST.Text = "";
            txtGROOMQQ.Text = "";
            txtHOUSEADDRESS.Text = "";
            //以下信息可以通过tbody控制
            txtMARRIAGECAR.Text = "";
            txtHotelManage.Text = "";
            txtRANK.Text = "";
            txtTABLENUM.Text = "";
            txtWEDDING.Text = "";
            txtYOUNGER.Text = "";
            txtELDER.Text = "";
            Text1.Value = "";
            btn_Submit.Visible = true;
            Button1.Visible = false;
            hidOrderID.Value = "";
            bindFalg = false;
        }

        #endregion


        #region 导出Word
        protected void GetWord_Click(object sender, EventArgs e)
        {
            string strGUID = System.Guid.NewGuid().ToString();
            Object Nothing = System.Reflection.Missing.Value;
            //取得Word文件保存路径 
            object filename = Server.MapPath("Order//File//") + strGUID + ".docx";
            try
            {
                //创建一个名为WordApp的组件对象 
                Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
                //网络上有写代码中直接使用Word.Application WordApp = new ApplicationClass(); 但我在实际编写中总是出现错误。
                //创建一个名为WordDoc的文档对象 
                Microsoft.Office.Interop.Word.Document WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
                //增加一表格 


                GetData();
                var dataSource = (from v in data.AsEnumerable() select new { a = v.Field<string>("PROJECT_ID"), b = v.Field<string>("PROJECT_NAME"), c = v.Field<int?>("PRICE"), d = v.Field<string>("PROJECTTYPE_NAME") }).Distinct();
                DataTable datable = new DataTable();
                datable = ConvertToTable(dataSource);
                if (datable.Rows.Count > 0)
                {
                    BLL.Progect.T_PUB_PROJECTFILE projectBll = new BLL.Progect.T_PUB_PROJECTFILE();
                    DataTable ImageTable = projectBll.GetProjectImageUrl(all_ProjectID);
                    AddUrl(datable, ImageTable);
                }
                ArrayList nameArry = new ArrayList();
                ArrayList TypeArry = new ArrayList();
                ArrayList priceArry = new ArrayList();
                ArrayList urlArry = new ArrayList();
                ArrayList numArry = new ArrayList();
                ArrayList totalArry = new ArrayList();

                for (int i = 0; i < datable.Rows.Count; i++)
                {
                    string strType = datable.Rows[i]["d"].ToString();
                    string strName = datable.Rows[i]["b"].ToString();
                    string strUrl = datable.Rows[i]["URLThumbnail"].ToString();
                    if (strUrl != "")
                    {
                        strUrl = strUrl.Substring(6, strUrl.Length - 6);
                        strUrl = strUrl.Replace('/', '\\');
                    }
                    //strUrl = strUrl.Replace('/', '\\');
                    string strPrice = datable.Rows[i]["c"].ToString();
                    string strNum = datable.Rows[i]["Number"].ToString();
                    string total = "";
                    if (strPrice != "" && strNum != "")
                    {
                        total = (Convert.ToInt32(strPrice) * Convert.ToInt32(strNum)).ToString();
                    }

                    int typeIndex = TypeArry.IndexOf(strType);
                    if (typeIndex >= 0)
                    {
                        nameArry[typeIndex] = nameArry[typeIndex] + " , " + strName;
                    }
                    else
                    {
                        TypeArry.Add(strType);
                        nameArry.Add(strName);
                        priceArry.Add(strPrice);
                        urlArry.Add(strUrl);
                        numArry.Add(strNum);
                        totalArry.Add(total);
                    }
                }

                ArrayList materialURL = new ArrayList();
                ArrayList materialName = new ArrayList();
                ArrayList materialType = new ArrayList();
                ArrayList materialNum = new ArrayList();
                DataRow[] rowstemp;
                string strWhere;
                for (int i = 0; i < data.Rows.Count; i++)
                {
                    string strType = data.Rows[i]["TYPE_NAME"].ToString();
                    string strName = data.Rows[i]["MATERIAL_NAME"].ToString();
                    string strUrl = data.Rows[i]["IMAGEURL"].ToString();
                    if (strUrl != "")
                    {
                        strUrl = strUrl.Substring(6, strUrl.Length - 6);
                        strUrl = strUrl.Replace('/', '\\');
                    }
                    int intNum = 0;
                    string strNUm = data.Rows[i]["NUM"].ToString();
                    if (strNUm != "")
                    {
                        int.TryParse(strNUm, out intNum);
                    }
                    int intNumber = 0;
                    strWhere = string.Format(" a='{0}'", data.Rows[i]["PROJECT_ID"]);
                    rowstemp = datable.Select(strWhere);
                    if (rowstemp.Length > 0)
                    {
                        int.TryParse(rowstemp[0]["Number"].ToString(), out intNumber);
                    }


                    string strNum = (intNum * intNumber).ToString();
                    int typeIndex = TypeArry.IndexOf(strType);
                    if (typeIndex >= 0)
                    {
                        nameArry[typeIndex] = nameArry[typeIndex] + " , " + strName;
                    }
                    else
                    {
                        materialType.Add(strType);
                        materialName.Add(strName);
                        materialURL.Add(strUrl);
                        materialNum.Add(strNum);
                    }
                }

                int Projectcount = TypeArry.Count;
                int Materialcount = materialName.Count;

                Object start = Type.Missing;
                Object end = Type.Missing;
                Object unit = Type.Missing;
                Object count = Type.Missing;
                WordDoc.Range(ref start, ref end).Delete(ref unit, ref count);
                string strInfo = "订单明细表";
                start = 0;
                end = 0;
                WordDoc.Range(ref start, ref end).InsertAfter(strInfo);
                WordDoc.Range(ref start, ref end).Font.Name = "Verdana";
                WordDoc.Range(ref start, ref end).Font.Size = 20;
                WordDoc.Range(ref start, ref end).ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                start = strInfo.Length;
                end = strInfo.Length;
                WordDoc.Range(ref start, ref end).InsertParagraphAfter();//插入回车  

                object what = Microsoft.Office.Interop.Word.WdUnits.wdLine;
                count = 1;
                WordApp.Selection.MoveDown(ref what, ref count, ref Nothing);
                WordApp.Selection.TypeParagraph();

                WordDoc.Tables.Add(WordApp.Selection.Range, 16, 4, ref Nothing, ref Nothing);
                Microsoft.Office.Interop.Word.Table table = WordDoc.Tables[1];
                table.Range.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                count = 16;
                WordApp.Selection.MoveDown(ref what, ref count, ref Nothing);
                WordApp.Selection.TypeParagraph();
                WordDoc.Tables.Add(WordApp.Selection.Range, Projectcount + 2, 6, ref Nothing, ref Nothing);
                Microsoft.Office.Interop.Word.Table tableProject = WordDoc.Tables[2];
                tableProject.Range.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                count = Projectcount + 2;
                WordApp.Selection.MoveDown(ref what, ref count, ref Nothing);
                WordApp.Selection.TypeParagraph();
                WordDoc.Tables.Add(WordApp.Selection.Range, Materialcount + 2, 4, ref Nothing, ref Nothing);
                Microsoft.Office.Interop.Word.Table tableMaterial = WordDoc.Tables[3];
                tableMaterial.Range.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                #region 操作表格样式
                //设置表格样式
                table.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleThickThinLargeGap;
                table.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;

                tableProject.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleThickThinLargeGap;
                tableProject.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;

                tableMaterial.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleThickThinLargeGap;
                tableMaterial.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                #endregion

                //在表格第一单元格中添加自定义的文字内容 
                table.Cell(1, 1).Range.Text = "庆典类型：";
                table.Cell(1, 1).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                table.Cell(1, 2).Range.Text = orderType.SelectedItem.Text;
                table.Cell(1, 3).Range.Text = "服务日期：";
                table.Cell(1, 3).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                table.Cell(1, 4).Range.Text = d12.Value;
                table.Cell(2, 1).Range.Text = "新郎姓名：";
                table.Cell(2, 1).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                table.Cell(2, 2).Range.Text = txtGROOM_NAME.Text;
                table.Cell(2, 3).Range.Text = "新娘姓名：";
                table.Cell(2, 3).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                table.Cell(2, 4).Range.Text = txtBRIDE_NAME.Text;
                table.Cell(3, 1).Range.Text = "新郎年龄：";
                table.Cell(3, 1).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                table.Cell(3, 2).Range.Text = txtGROOMAGE.Text;
                table.Cell(3, 3).Range.Text = "新娘年龄：";
                table.Cell(3, 3).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                table.Cell(3, 4).Range.Text = txtBRIDEAGE.Text;
                table.Cell(4, 1).Range.Text = "新郎电话：";
                table.Cell(4, 1).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                table.Cell(4, 2).Range.Text = txtGROOMPHONE.Text;
                table.Cell(4, 3).Range.Text = "新娘电话：";
                table.Cell(4, 3).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                table.Cell(4, 4).Range.Text = txtBRIDEPHONE.Text;
                table.Cell(5, 1).Range.Text = "新郎QQ：";
                table.Cell(5, 1).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                table.Cell(5, 2).Range.Text = txtGROOMQQ.Text;
                table.Cell(5, 3).Range.Text = "新娘QQ：";
                table.Cell(5, 3).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                table.Cell(5, 4).Range.Text = txtBRIDEQQ.Text;
                table.Cell(6, 1).Range.Text = "新房地址：";
                table.Cell(6, 1).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                table.Cell(6, 2).Range.Text = txtHOUSEADDRESS.Text;
                table.Cell(6, 3).Range.Text = "娘家地址";
                table.Cell(6, 3).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                table.Cell(6, 4).Range.Text = txtBRIDEADDRESS.Text;
                table.Cell(7, 1).Range.Text = "服务地址：";
                table.Cell(7, 1).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                table.Cell(7, 2).Range.Text = Text1.Value;
                table.Cell(7, 3).Range.Text = "酒店接待人员：";
                table.Cell(7, 3).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                table.Cell(7, 4).Range.Text = txtHotelManage.Text;
                table.Cell(8, 1).Range.Text = "新郎职务：";
                table.Cell(8, 1).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                table.Cell(8, 2).Range.Text = txtGROOMPOST.Text;
                table.Cell(8, 3).Range.Text = "新娘职务：";
                table.Cell(8, 3).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                table.Cell(8, 4).Range.Text = txtBRIDEPOST.Text;
                table.Cell(9, 1).Range.Text = "婚纱照交接情况：";
                table.Cell(9, 1).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                table.Cell(9, 2).Range.Text = txtWEDDING.Text;
                table.Cell(9, 3).Range.Text = "婚车负责人：";
                table.Cell(9, 3).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                table.Cell(9, 4).Range.Text = txtMARRIAGECAR.Text;
                table.Cell(10, 1).Range.Text = "桌数：";
                table.Cell(10, 1).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                table.Cell(10, 2).Range.Text = txtTABLENUM.Text;
                table.Cell(10, 3).Range.Text = "来宾中长辈数：";
                table.Cell(10, 3).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                table.Cell(10, 4).Range.Text = txtELDER.Text;
                table.Cell(11, 1).Range.Text = "新房地址：";
                table.Cell(11, 1).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                table.Cell(11, 2).Range.Text = txtRANK.Text;
                table.Cell(11, 3).Range.Text = "来宾中后辈数：";
                table.Cell(11, 3).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                table.Cell(11, 4).Range.Text = txtYOUNGER.Text;

                //风格初始化
                table.Cell(12, 2).Merge(table.Cell(12, 3));
                table.Cell(12, 2).Merge(table.Cell(12, 3));
                table.Cell(12, 1).Range.Text = "风格：";
                table.Cell(12, 1).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                object startLocation = table.Cell(12, 2).Range.Start;
                object endLocation = table.Cell(12, 2).Range.Start;
                BLL.SysManage.T_PUB_DICTIONARY bll = new BLL.SysManage.T_PUB_DICTIONARY();
                List<Model.SysManage.T_PUB_DICTIONARY> il = bll.GetListArray(" FLAG = 1 and PARENT_ID = 5 order by ORDER_ID");
                int stylecount = il.Count();
                int stylerow = (stylecount - 1) / 5 + 1;
                // Supply a Start and End value for the Range. 
                Microsoft.Office.Interop.Word.Range rng = WordDoc.Range(ref startLocation, ref endLocation);
                table.Cell(12, 2).Range.Tables.Add(rng, stylerow, 5, ref Nothing, ref Nothing);
                Microsoft.Office.Interop.Word.Table styletable = WordDoc.Tables[1].Tables[1];
                string styles = "," + hidStytle.Value + ",";
                int tempValue;
                for (int j = 0; j <= (stylecount - 1) / 5; j++)
                {
                    int i = 0;
                    for (; i < 5 && 5 * j + i < stylecount; i++)
                    {
                        tempValue = 5 * j + i;
                        string strName = il.ElementAt(tempValue).NAME;
                        string strId = il.ElementAt(tempValue).ID.ToString();
                        styletable.Cell(j + 1, i + 1).Range.Text = strName;
                        object Locationstart = styletable.Cell(j + 1, i + 1).Range.Start;
                        object Locationend = styletable.Cell(j + 1, i + 1).Range.Start;
                        Microsoft.Office.Interop.Word.Range rngstyle = WordDoc.Range(ref Locationstart, ref Locationend);
                        Microsoft.Office.Interop.Word.Bookmark bookmark1 = WordDoc.Bookmarks.Add(strName, rngstyle);
                        object fontname = "Wingdings 2";
                        object uic = true;
                        object lblmark = strName;
                        if (styles.Contains("," + strId + ","))
                        {
                            WordDoc.Bookmarks.get_Item(ref lblmark).Range.InsertSymbol(-4014, ref fontname, ref uic, ref Nothing);//选中-4014，没选中-4015 
                        }
                        else
                        {
                            WordDoc.Bookmarks.get_Item(ref lblmark).Range.InsertSymbol(-4015, ref fontname, ref uic, ref Nothing);
                        }
                    }
                    //if ((5 - i) > 0)
                    //{
                    //    int sy = 5 - i;

                    //}
                }

                table.Cell(13, 1).Range.Text = "备注：";
                table.Cell(13, 1).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                table.Cell(13, 2).Merge(table.Cell(13, 3));
                table.Cell(13, 2).Merge(table.Cell(13, 3));
                table.Cell(13, 2).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                table.Cell(13, 2).Range.Text = txtOther.Text;
                table.Cell(14, 1).Range.Text = "市面金额：";
                table.Cell(14, 1).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                table.Cell(14, 2).Merge(table.Cell(14, 3));
                table.Cell(14, 2).Merge(table.Cell(14, 3));
                table.Cell(14, 2).Range.Text = string.Format("市面金额:{0} 签单金额：{1} 定金 :{2} 未交金额:{3}", txtTotal.Text, textRealTotal.Text, txtDinJin.Text, txtUnpaid.Text);
                table.Cell(15, 1).Range.Text = "接待人员：";
                table.Cell(15, 1).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                table.Cell(15, 2).Range.Text = Session["USER_NAME"].ToString();
                table.Cell(15, 3).Range.Text = "业务来源：";
                table.Cell(15, 3).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                if (dropFrom.SelectedItem != null)
                {
                    table.Cell(15, 4).Range.Text = dropFrom.SelectedItem.Text;
                }
                table.Cell(16, 1).Range.Text = "纪念类型：";
                table.Cell(16, 1).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                if (MemorialType.SelectedValue != "0")
                {
                    table.Cell(16, 2).Range.Text = MemorialType.SelectedItem.Text;
                }
                table.Cell(16, 3).Range.Text = "纪念日期：";
                table.Cell(16, 3).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                table.Cell(16, 4).Range.Text = MemorialDate.Value;

                tableProject.Cell(1, 1).Merge(tableProject.Cell(1, 2));
                tableProject.Cell(1, 1).Merge(tableProject.Cell(1, 2));
                tableProject.Cell(1, 1).Merge(tableProject.Cell(1, 2));
                tableProject.Cell(1, 1).Merge(tableProject.Cell(1, 2));
                tableProject.Cell(1, 1).Merge(tableProject.Cell(1, 2));
                tableProject.Cell(1, 1).Range.Text = "项目明细";
                tableProject.Cell(2, 1).Range.Text = "图片";
                tableProject.Cell(2, 2).Range.Text = "项目名称";
                tableProject.Cell(2, 3).Range.Text = "项目类型";
                tableProject.Cell(2, 4).Range.Text = "单价";
                tableProject.Cell(2, 5).Range.Text = "数量";
                tableProject.Cell(2, 6).Range.Text = "合计";
                string path = HostingEnvironment.ApplicationPhysicalPath;
                for (int i = 1; i <= Projectcount; i++)
                {
                    string imageurl = path + urlArry[i - 1].ToString();
                    if (File.Exists(imageurl))
                    {
                        object Anchor = tableProject.Cell(i + 2, 1).Range;
                        WordDoc.Application.ActiveDocument.InlineShapes.AddPicture(imageurl, ref Nothing, ref Nothing, ref Anchor);
                        WordDoc.Application.ActiveDocument.InlineShapes[1].Width = 60;//图片宽度
                        WordDoc.Application.ActiveDocument.InlineShapes[1].Height = 60;//图片高度
                        //Microsoft.Office.Interop.Word.Shape s = WordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();//将图片设置为四周环绕型
                        //s.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapSquare;
                    }
                    else
                    {
                        object Anchor = tableProject.Cell(i + 2, 1).Range;
                        WordDoc.Application.ActiveDocument.InlineShapes.AddPicture(path + "Images\\Element\\nophoto.bmp", ref Nothing, ref Nothing, ref Anchor);
                        WordDoc.Application.ActiveDocument.InlineShapes[1].Width = 60;//图片宽度
                        WordDoc.Application.ActiveDocument.InlineShapes[1].Height = 60;//图片高度
                        //Microsoft.Office.Interop.Word.Shape s = WordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();//将图片设置为四周环绕型
                        //s.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapSquare;
                    }
                    tableProject.Cell(i + 2, 2).Range.Text = nameArry[i - 1].ToString();
                    tableProject.Cell(i + 2, 3).Range.Text = TypeArry[i - 1].ToString();
                    tableProject.Cell(i + 2, 4).Range.Text = priceArry[i - 1].ToString();
                    tableProject.Cell(i + 2, 5).Range.Text = numArry[i - 1].ToString();
                    tableProject.Cell(i + 2, 6).Range.Text = totalArry[i - 1].ToString();
                }

                //填充材料表
                tableMaterial.Cell(1, 1).Merge(tableMaterial.Cell(1, 2));
                tableMaterial.Cell(1, 1).Merge(tableMaterial.Cell(1, 2));
                tableMaterial.Cell(1, 1).Merge(tableMaterial.Cell(1, 2));
                tableMaterial.Cell(1, 1).Range.Text = "元素明细";
                tableMaterial.Cell(2, 1).Range.Text = "图片";
                tableMaterial.Cell(2, 2).Range.Text = "元素名称";
                //tableProject.Columns[2].Width = 200;
                tableMaterial.Cell(2, 3).Range.Text = "元素类型";
                tableMaterial.Cell(2, 4).Range.Text = "数量";
                //string path = HostingEnvironment.ApplicationPhysicalPath;
                //path = path.Substring(0, path.Length - 6);
                for (int i = 1; i <= Materialcount; i++)
                {
                    //tableProject.Cell(i + 1, 1).Range.Text = urlArry[i - 1].ToString();
                    string imageurl = path + materialURL[i - 1].ToString();
                    if (File.Exists(imageurl))
                    {
                        object Anchor = tableMaterial.Cell(i + 2, 1).Range;
                        WordDoc.Application.ActiveDocument.InlineShapes.AddPicture(imageurl, ref Nothing, ref Nothing, ref Anchor);
                        WordDoc.Application.ActiveDocument.InlineShapes[1].Width = 60;//图片宽度
                        WordDoc.Application.ActiveDocument.InlineShapes[1].Height = 60;//图片高度
                        //Microsoft.Office.Interop.Word.Shape s = WordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();//将图片设置为四周环绕型
                        //s.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapSquare;
                    }
                    else
                    {
                        object Anchor = tableMaterial.Cell(i + 2, 1).Range;
                        WordDoc.Application.ActiveDocument.InlineShapes.AddPicture(path + "Images\\Element\\nophoto.bmp", ref Nothing, ref Nothing, ref Anchor);
                        WordDoc.Application.ActiveDocument.InlineShapes[1].Width = 60;//图片宽度
                        WordDoc.Application.ActiveDocument.InlineShapes[1].Height = 60;//图片高度
                        //Microsoft.Office.Interop.Word.Shape s = WordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();//将图片设置为四周环绕型
                        //s.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapSquare;
                    }
                    tableMaterial.Cell(i + 2, 2).Range.Text = materialName[i - 1].ToString();
                    tableMaterial.Cell(i + 2, 3).Range.Text = materialType[i - 1].ToString();
                    tableMaterial.Cell(i + 2, 4).Range.Text = materialNum[i - 1].ToString();
                }

                //在文档空白地方添加文字内容 
                // WordDoc.Paragraphs.Last.Range.Text = "Wellcome To Aspxcn.Com";
                //将WordDoc文档对象的内容保存为DOC文档 
                WordDoc.SaveAs(ref filename, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing,
                ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
                //关闭WordDoc文档对象 
                WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
                //关闭WordApp组件对象 
                WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
                string strWordName = txtGROOM_NAME.Text + "_" + txtBRIDE_NAME.Text + "订单.doc";
                Response.Redirect("Order/DownLoad.aspx?filePath=" + filename + "&name=" + strWordName);
            }
            catch { }
            finally
            {
                //杀死打开的word进程
                Process myProcess = new Process();
                Process[] wordProcess = Process.GetProcessesByName("winword");
                try
                {
                    foreach (Process pro in wordProcess) //这里是找到那些没有界面的Word进程
                    {
                        IntPtr ip = pro.MainWindowHandle;

                        string str = pro.MainWindowTitle; //发现程序中打开跟用户自己打开的区别就在这个属性
                        //用户打开的str 是文件的名称，程序中打开的就是空字符串
                        if (string.IsNullOrEmpty(str))
                        {
                            pro.Kill();
                        }
                    }
                    hidRunState.Value = "0";
                }
                catch (Exception ex)
                {
                }
            }
        }
        #endregion
    }
}